package io.openkunlun.javadsl.client;

import io.grpc.*;
import io.openkunlun.javadsl.DaprContext;

/**
 * @author Srowen
 * @date Created on 2022/3/15
 * @description
 */
public class DaprClientContextInterceptor implements ClientInterceptor {

    @Override
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions, Channel channel) {
        return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(channel.newCall(methodDescriptor, callOptions)) {
            @Override
            public void start(Listener<RespT> responseListener, Metadata headers) {
                io.openkunlun.javadsl.Context context = io.openkunlun.javadsl.Context.current();
                Metadata metadata = context.getLocal(DaprContext.METADATA);
                if (null != metadata) {
                    headers.merge(metadata);
                }
                super.start(responseListener, headers);
            }
        };
    }
}
